<script setup lang="ts">
import { ref, h, computed, toRaw } from "vue";
import { RollbackOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
import type { projectSetting } from "./types";
const project = ref("")
let projectsData = ref<{ [key: string]: projectSetting }>({})
let data = localStorage.getItem("projects")
if (data != null) {
  projectsData.value = JSON.parse(data)
}

function delProject(project: string) {
  delete projectsData.value[project]
  localStorage.setItem("projects", JSON.stringify(projectsData.value))
}
async function addProject() {
  let info = await window.api.selectFile(0)
  if (info != null) {
    let arr = info.split('/')
    let name = ""
    if (arr[arr.length - 3] == 'api') {
      name = arr[arr.length - 2].split('-')[0]
    } else name = arr[arr.length - 3].split('-')[0]
    projectsData.value[name] = { path: info, dbPath: '', exclude: ['overlord', 'heracles', 'flyway', 'armor'] }
    localStorage.setItem("projects", JSON.stringify(projectsData.value))
  }
}
async function selectProject(name: string) {
  let config = toRaw(projectsData.value[name])
  if (config.dbPath != '') {
    window.db = await window.api.readDb(config.dbPath, config.exclude)
  } else window.db = {}
  project.value = name
}
const projectList = computed(() => {
  return Object.keys(projectsData.value)
})

//#region 设置
let isShowSetting = ref(false)
let settingData = ref<projectSetting>({ path: '', dbPath: '', exclude: [] })
let settingDataKey = ""
function showSetting(key: string) {
  isShowSetting.value = true
  settingData.value = structuredClone(toRaw(projectsData.value[key]))
  settingDataKey = key
}
function saveSetting() {
  projectsData.value[settingDataKey] = settingData.value
  isShowSetting.value = false
  localStorage.setItem("projects", JSON.stringify(projectsData.value))
}
function delExclude(index: number) {
  settingData.value.exclude.splice(index, 1)
}
function addExclude() {
  settingData.value.exclude.push("")
}
async function selectDb() {
  let info = await window.api.selectFile(1)
  if (info != null) {
    settingData.value.dbPath = info
  }
}
//#endregion
</script>

<template>
  <div v-show="project != ''">
    <a-button class="back-btn" type="primary" @click="project = ''" :icon="h(RollbackOutlined)" />
    <ProjectView :project="projectsData[project]"></ProjectView>
  </div>
  <div v-show="project == ''">
    <a-list bordered :data-source="projectList">
      <template #renderItem="{ item }">
        <a-list-item @click="selectProject(item)">{{ item }}<a-button danger class="float-right"
            @click.stop="delProject(item)" :icon="h(DeleteOutlined)" /><a-button class="float-right"
            @click.stop="showSetting(item)">
            <SettingOutlined />
          </a-button>
        </a-list-item>
      </template>
      <template #footer>
        <div><a-button type="primary" @click="addProject" :icon="h(PlusOutlined)" /></div>
      </template>
    </a-list>
    <a-modal v-model:open="isShowSetting" title="项目配置" style="min-width: 600px;" @ok="saveSetting">
      <a-form autocomplete="off">
        <a-form-item label="项目路径">
          <a-input v-model:value="settingData.path" disabled />
        </a-form-item>
        <a-form-item label="数据库路径">
          <a-input-search v-model:value="settingData.dbPath" disabled>
            <template #enterButton>
              <a-button type="primary" @click="selectDb()">
                选择数据库文件
              </a-button>
            </template>
          </a-input-search>
        </a-form-item>
        <a-form-item v-for="(_, index) in settingData.exclude" :key="index">
          <a-input v-model:value="settingData.exclude[index]">
            <template v-if="settingData.exclude.length > 1" #addonAfter>
              <MinusCircleOutlined @click="delExclude(index)" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" style="width: 60%" @click="addExclude()">
            <PlusOutlined />
            添加数据库忽略哪些表（关键字）
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  height: 100%;
}

.float-right {
  float: right;
}

.float-left {
  float: left;
}

.back-btn {
  position: fixed;
  left: 20px;
  top: 20px;
  z-index: 100;
}
</style>